package com.atguigu.springcloud.controller;


import com.atguigu.springcloud.entity.CommonResult;
import com.atguigu.springcloud.entity.Payment;
import com.atguigu.springcloud.service.IPaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tjf
 * @since 2021-12-09
 */
@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {
    private final IPaymentService paymentService;

    private final DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

//    public PaymentController(IPaymentService paymentService) {
//        this.paymentService = paymentService;
//    }

    public PaymentController(IPaymentService paymentService, DiscoveryClient discoveryClient) {
        this.paymentService = paymentService;
        this.discoveryClient = discoveryClient;
    }

    @PostMapping("/create")
    public CommonResult<Payment> create(@RequestBody Payment payment) {
        boolean saved = paymentService.save(payment);
        log.info("*****插入结果：" + (saved ? "成功" : "失败"));
        if (saved) {
            return new CommonResult<>(200, "插入数据库成功, serverPort: " + serverPort);
        } else {
            return new CommonResult<>(444, "插入数据库失败");
        }
    }

    @GetMapping("/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Integer id) {
        Payment payment = paymentService.getById(id);
        log.info("*****查询结果：" + payment);
        if (payment != null) {
            return new CommonResult<>(200, "查询数据库成功, serverPort: " + serverPort, payment);
        } else {
            return new CommonResult<>(444, "没有对应记录ID" + id);
        }
    }

    @GetMapping("/discovery")
    public DiscoveryClient discovery() {
        List<String> services = discoveryClient.getServices();
        services.forEach(service -> log.info("*****service: " + service));
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        instances.forEach(instance -> log.info(instance.getInstanceId() + "\t"
                + instance.getHost() + "\t"
                + instance.getPort() + "\t"
                + instance.getUri()));
        return discoveryClient;
    }

    @GetMapping("/lb")
    public String getPaymentLB() {
        return serverPort;
    }

    @GetMapping("/feign/timeout")
    public String paymentFeignTimeout() {
        try {
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }
}

